import {
    modules as storeModules
} from "@/store/index"

import { RootState } from "@/store/interface";
import AppState from "@/store/modules/app";
import UserState from "@/store/modules/user";
import LayoutState from "@/store/modules/layout";

// 拿到所有已知 仓库名
type storeKeys = keyof RootState

// 各个模块的 action
type AppActions = keyof typeof AppState.actions;
type UserActions = keyof typeof UserState.actions;
type LayoutActions = keyof typeof LayoutState.actions;

// 所有模块 action 映射类型
interface ActionsMapType {
    readonly app: {
        readonly [key in AppActions]: string;
    },
    readonly user: {
        readonly [key in UserActions]: string;
    },
    readonly layout: {
        readonly [key in LayoutActions]: string;
    }
};

// 所有模块 action 方法 
const storeModulesAactions = Object.entries(storeModules).map(([key, module]) => ({ [key]: Object.keys(module.actions) }))

/**  
 * @description 所有模块可分发（dispatch）的 action 映射。
 * @example 
 * // 直接使用
 * dispatch(moduleActionDispatchMap.模块.action); // 等价于 dispatch("模块/action")  
 *  
 * // 解构指定模块
 * const { 模块 } = moduleActionDispatchMap;  
 * dispatch(模块.action); // 同样等价于 dispatch("模块/action")  
 */
const moduleActionDispatchMap: ActionsMapType = storeModulesAactions.reduce((newStore, actionsObj) => {
    Object.entries(actionsObj).forEach(([name, actions]) => {

        actions.forEach((action) => {
            (newStore[name as storeKeys] as ActionsMapType[storeKeys]) = {
                // 保留前面添加的 action
                ...newStore[name as storeKeys],

                // 添加 action
                [action]: `${name}/${action}`
            }
        })
    })

    return newStore
}, {} as ActionsMapType)

export {
    moduleActionDispatchMap
}